﻿using Microsoft.AspNetCore.Mvc.Filters;
using System.Linq;
using System.Threading.Tasks;
using X23.EFCore;
using X23.Extensions.AttributeExtensions;

namespace X23.Extensions.FilterExtensions
{
    public class UnitOfWorkFilter : IAsyncActionFilter
    {
        public const string UowHttpContextKey = "X23UnitOfWork";
        private readonly EFCoreContext _eFCoreContext;

        public UnitOfWorkFilter(EFCoreContext eFCoreContext)
        {
            _eFCoreContext = eFCoreContext;
        }
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            #region 通过特性（UnitOfWorkAttribute）以后可以处理事务开启
            bool isDisabled = false;
            var uowAttribute = ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor).MethodInfo.GetCustomAttributes(true).OfType<UnitOfWorkAttribute>().FirstOrDefault();
            if (uowAttribute != null && uowAttribute.IsDisabled)
            {
                isDisabled = true;
            }
            #endregion

            //var currentTransaction = _eFCoreContext.Database.CurrentTransaction;
            //if (currentTransaction == null)
            //{
            //    currentTransaction = isDisabled ? null : _eFCoreContext.Database.BeginTransaction();
            //}
            var currentTransaction = isDisabled ? null :await _eFCoreContext.Database.BeginTransactionAsync();

            var data = await next();
            if (currentTransaction != null)
            {
                if (data.Exception == null)
                {
                    await currentTransaction.CommitAsync();
                }
                await currentTransaction.DisposeAsync();
            }
        }
    }
}
